<template>
  <div class="login-main">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户登陆</span>
        </div>
      </template>
      <div class="card-body">
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="70px" class="demo-ruleForm">
          <el-form-item label="邮箱" prop="username">
            <el-input v-model="ruleForm.username" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)" :style="{ width: '100%' }" color="#035D1C">登陆</el-button>
          </el-form-item>
        </el-form>
        <p style="text-align: center;">没有账号? <router-link to="/register">去注册</router-link>.</p>
      </div>
    </el-card>
    <Verify mode="pop" :captchaType="captchaType" :imgSize="{ width: '400px', height: '200px' }" ref="verify"
      @success="handleSuccess"></Verify>
  </div>
</template>
  
<script lang="ts" setup>
import { FormInstance, FormRules } from 'element-plus';
import { LoginAPI } from '../api/user.ts'
import { useRouter } from 'vue-router'

const router = useRouter()

const ruleFormRef = ref<FormInstance>()

const checkEmail = (_rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入邮箱'))
  }
  const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(value)) {
    return callback(new Error('请输入有效的邮箱'))
  }
  callback()
}

const validatePass = (_rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入密码'))
  }
  callback()
}

const ruleForm = reactive({
  password: '',
  username: ''
})

const rules = reactive<FormRules<typeof ruleForm>>({
  password: [{ validator: validatePass, trigger: 'blur' }],
  username: [{ validator: checkEmail, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      onShow('blockPuzzle')

    } else {
      console.log('error submit!')
      return false
    }
  })
}


const verify = ref<null | { show: () => void }>(null);
const captchaType = ref('');
const onShow = (type: string) => {
  if (!ruleForm.username) {
    ElMessage.error("请输入邮箱")
    return
  }
  const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(ruleForm.username)) {
    ElMessage.error("请输入有效邮箱")
    return
  }
  captchaType.value = type;
  if (verify.value !== null) {
    verify.value.show();
  }
}

const handleSuccess = (res: any) => {
  LoginAPI({
    username: ruleForm.username,
    password: ruleForm.password,
    captchaVerification: res.captchaVerification
  })
      .then((res) => {
        if(res.code === 200&&res.msg!==null){
          ElMessage.success(res.msg)
          localStorage.setItem("x-auth-token",res.data.token)
          localStorage.setItem("userType",res.data.userType)
          localStorage.setItem("isLoggedIn","1")
          localStorage.setItem("userId",res.data.userId)
          sessionStorage.setItem("username",res.data.username)
          sessionStorage.setItem("ownName",res.data.nickname)
          router.push("/")
        }
        if(res.code === 100&&res.msg!==null){
          ElMessage.error(res.msg)
        }

    })
}
</script>
  
<style scoped>
.card-header {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: large;
  font-weight: bold;
}

.card-body {
  width: 93%;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card {
  width: 350px;
  height: 290px;
}

.login-main {
  background-image: url("../assets/img/rice.png");
  background-size: cover;
  background-position: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.input-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
  